"""
多线程和多进程对比

核心知识点：
    1.耗CPU操作，用多进程编程（多进程优于多线程）
    2.对于IO操作来说，使用多线程编程（多线程优于多进程）
    3.进程切换代价要高于线程
"""

import time
from concurrent.futures import ThreadPoolExecutor, as_completed, ProcessPoolExecutor


def fib(n):
    if n <= 2:
        return 1
    return fib(n - 1) + fib(n - 2)


def use_thread():
    with ThreadPoolExecutor(3) as executor:
        all_task = [executor.submit(fib, (num)) for num in range(20, 25)]
        start_time = time.time()

        for future in as_completed(all_task):
            data = future.result()
            print("结果为：", data)

        end_time = time.time()
        print("耗时：{} s".format(end_time - start_time))
        # 输出结果：
        """
        结果为： 6765
        结果为： 10946
        结果为： 17711
        结果为： 28657
        结果为： 46368
        耗时：0.7788751125335693 s
        """


def use_process():
    with ProcessPoolExecutor(3) as executor:
        all_task = [executor.submit(fib, (num)) for num in range(20, 25)]
        start_time = time.time()

        for future in as_completed(all_task):
            data = future.result()
            print("结果为：", data)

        end_time = time.time()
        print("耗时：{} s".format(end_time - start_time))
        # 输出结果：
        """
        结果为： 6765
        结果为： 10946
        结果为： 17711
        结果为： 28657
        结果为： 46368
        耗时：0.6567130088806152 s
        """


def random_sleep(n):
    time.sleep(n)
    return n


def use_io_thread():
    with ThreadPoolExecutor(3) as executor:
        all_task = [executor.submit(random_sleep, (num)) for num in range(1, 5)]
        start_time = time.time()

        for future in as_completed(all_task):
            data = future.result()
            print("结果为：", data)

        end_time = time.time()
        print("耗时：{} s".format(end_time - start_time))
        # 输出结果：
        """
        结果为： 1
        结果为： 2
        结果为： 3
        结果为： 4
        耗时：5.000002861022949 s
        """


def use_io_process():
    with ProcessPoolExecutor(3) as executor:
        all_task = [executor.submit(random_sleep, (num)) for num in range(1, 5)]
        start_time = time.time()

        for future in as_completed(all_task):
            data = future.result()
            print("结果为：", data)

        end_time = time.time()
        print("耗时：{} s".format(end_time - start_time))
        # 输出结果：
        """
        结果为： 1
        结果为： 2
        结果为： 3
        结果为： 4
        耗时：5.082677125930786 s
        """


if __name__ == '__main__':
    # use_thread()
    # use_process()
    # use_io_thread()
    use_io_process()
